<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.2" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="js定时器," />





  <link rel="alternate" href="/atom.xml" title="OBKoro1's Blog" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.2" />






<meta name="description" content="写在前面：在js应用中，定时器的作用就是可以设定当到达一个时间来执行一个函数，或者每隔几秒重复执行某段函数。这里面涉及到了三个函数方法：setInterval()、setTimeout()、clearInterval()，本文将围绕这三种函数的用法，来实现定时器的功能，需要的朋友可以过来参考下，喜欢的可以点波赞，或者关注一下本人，希望对大家有所帮助。 定时器的应用需求：1.设定一个时间，当时间到达">
<meta name="keywords" content="js定时器">
<meta property="og:type" content="article">
<meta property="og:title" content="js定时器用法详解——setTimeout()、setInterval()、clearTimeout()、clearInterval()">
<meta property="og:url" content="http://yoursite.com/2017/10/11/js定时器用法详解——setTimeout-、setInterval-、clearTimeout-、clearInterval/index.html">
<meta property="og:site_name" content="OBKoro1&#39;s Blog">
<meta property="og:description" content="写在前面：在js应用中，定时器的作用就是可以设定当到达一个时间来执行一个函数，或者每隔几秒重复执行某段函数。这里面涉及到了三个函数方法：setInterval()、setTimeout()、clearInterval()，本文将围绕这三种函数的用法，来实现定时器的功能，需要的朋友可以过来参考下，喜欢的可以点波赞，或者关注一下本人，希望对大家有所帮助。 定时器的应用需求：1.设定一个时间，当时间到达">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://dn-mhke0kuv.qbox.me/c80c87f943e1ca56de5f.gif">
<meta property="og:image" content="https://dn-mhke0kuv.qbox.me/a8470e43082a064424f8">
<meta property="og:image" content="https://dn-mhke0kuv.qbox.me/0474fc212be6107c7c4b">
<meta property="og:image" content="https://dn-mhke0kuv.qbox.me/73b6c1d56121335f3a97.gif">
<meta property="og:updated_time" content="2019-06-15T06:19:47.632Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="js定时器用法详解——setTimeout()、setInterval()、clearTimeout()、clearInterval()">
<meta name="twitter:description" content="写在前面：在js应用中，定时器的作用就是可以设定当到达一个时间来执行一个函数，或者每隔几秒重复执行某段函数。这里面涉及到了三个函数方法：setInterval()、setTimeout()、clearInterval()，本文将围绕这三种函数的用法，来实现定时器的功能，需要的朋友可以过来参考下，喜欢的可以点波赞，或者关注一下本人，希望对大家有所帮助。 定时器的应用需求：1.设定一个时间，当时间到达">
<meta name="twitter:image" content="https://dn-mhke0kuv.qbox.me/c80c87f943e1ca56de5f.gif">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.2',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/2017/10/11/js定时器用法详解——setTimeout-、setInterval-、clearTimeout-、clearInterval/"/>





  <title>js定时器用法详解——setTimeout()、setInterval()、clearTimeout()、clearInterval() | OBKoro1's Blog</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?64d57d0b926bbd27431daa89d2e0a76b";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">OBKoro1's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-前端算法">
          <a href="/arithmetic/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-book"></i> <br />
            
            前端算法
          </a>
        </li>
      
        
        <li class="menu-item menu-item-博客最新更新">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            博客最新更新
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2017/10/11/js定时器用法详解——setTimeout-、setInterval-、clearTimeout-、clearInterval/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="OBKoro1">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/hand1.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="OBKoro1's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">js定时器用法详解——setTimeout()、setInterval()、clearTimeout()、clearInterval()</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-10-11T22:54:46+08:00">
                2017-10-11
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/js/" itemprop="url" rel="index">
                    <span itemprop="name">js</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2017/10/11/js定时器用法详解——setTimeout-、setInterval-、clearTimeout-、clearInterval/" class="leancloud_visitors" data-flag-title="js定时器用法详解——setTimeout()、setInterval()、clearTimeout()、clearInterval()">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  1,218 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  5分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="写在前面："><a href="#写在前面：" class="headerlink" title="写在前面："></a>写在前面：</h2><p>在js应用中，定时器的作用就是可以设定当到达一个时间来执行一个函数，或者每隔几秒重复执行某段函数。这里面涉及到了三个函数方法：setInterval()、setTimeout()、clearInterval()，本文将围绕这三种函数的用法，来实现定时器的功能，需要的朋友可以过来参考下，喜欢的可以点波赞，或者关注一下本人，希望对大家有所帮助。</p>
<h2 id="定时器的应用需求："><a href="#定时器的应用需求：" class="headerlink" title="定时器的应用需求："></a>定时器的应用需求：</h2><p>1.设定一个时间，当时间到达的时候执行函数————比如：倒计时跳转页面等等。</p>
<p>2.每隔一段时间重复执行某段函数————比如抢票软件，比如设定500毫秒就重复刷新一次页面等等。</p>
<h3 id="倒计时跳转实现demo："><a href="#倒计时跳转实现demo：" class="headerlink" title="倒计时跳转实现demo："></a>倒计时跳转实现demo：</h3><p><img src="https://dn-mhke0kuv.qbox.me/c80c87f943e1ca56de5f.gif" alt="里面也有实时显示时间的方法。"></p>
<h3 id="js定时器："><a href="#js定时器：" class="headerlink" title="js定时器："></a>js定时器：</h3><p>菜鸟教程中是这么说的——js 定时器有以下两个方法：</p>
<p><strong>setTimeout() ：</strong>在指定的毫秒数后调用函数或计算表达式。</p>
<p><strong>setInterval() ：</strong>按照指定的周期（以毫秒计）来调用函数或计算表达式。方法会不停地调用函数，直到 clearInterval() 被调用或窗口被关闭。</p>
<h3 id="使用语法："><a href="#使用语法：" class="headerlink" title="使用语法："></a>使用语法：</h3><p>setTimeout（）：setTimeout(code,millisec)</p>
<p>setInterval（）：setInterval(code,millisec[,”lang”])</p>
<p><strong>参数：</strong>code————要进行<strong>调用的函数或者要执行的代码串</strong>。millisec————<strong>时间</strong>（默认毫秒来计算），lang————可选。 JScript | VBScript | JavaScript（）</p>
<p>以上来自W3C：<a href="http://www.w3school.com.cn/jsref/met_win_settimeout.asp" target="_blank" rel="noopener">setTimeout() </a>,<a href="http://www.jb51.net/shouce/htmldom/jb51.net.htmldom/htmldom/met_win_setinterval.asp.html" target="_blank" rel="noopener">setInterval()</a></p>
<h2 id="然而setTimeout-、setInterval-的区别在于"><a href="#然而setTimeout-、setInterval-的区别在于" class="headerlink" title="然而setTimeout()、setInterval()的区别在于"></a>然而setTimeout()、setInterval()的区别在于</h2><p><strong>setTimeout()</strong>：当方法执行完成定时器就立即停止(但是定时器还在,只不过没用了);</p>
<p><strong>setInterval()：</strong>当方法执行完成,定时器并没有停止,以后每隔[interval]这么长的时间都会重新的执行对应的方法[function],直到我们手动清除定时器为止;</p>
<h3 id="意思就是："><a href="#意思就是：" class="headerlink" title="意思就是："></a>意思就是：</h3><p><strong>setTimeout()时间到了只会执行一次，setInterval()不会停止，会不间断的执行对应的函数</strong>，直到我们手动暂停或窗口被关闭。</p>
<p><strong>文章下面有demo讲解：</strong></p>
<hr>
<h2 id="那么如何暂停setTimeout-、setInterval"><a href="#那么如何暂停setTimeout-、setInterval" class="headerlink" title=" 那么如何暂停setTimeout()、setInterval():"></a> 那么如何暂停setTimeout()、setInterval():</h2><h3 id="clearTimeout（）取消由setTimeout-方法设置的-timeout。"><a href="#clearTimeout（）取消由setTimeout-方法设置的-timeout。" class="headerlink" title="clearTimeout（）取消由setTimeout() 方法设置的 timeout。"></a>clearTimeout（）取消由setTimeout() 方法设置的 timeout。</h3><p><img src="https://dn-mhke0kuv.qbox.me/a8470e43082a064424f8" alt=""></p>
<h3 id="clearInterval-，这个函数只有一个作用，就是暂停setInterval-调用函数。"><a href="#clearInterval-，这个函数只有一个作用，就是暂停setInterval-调用函数。" class="headerlink" title="clearInterval() ，这个函数只有一个作用，就是暂停setInterval()调用函数。"></a>clearInterval() ，这个函数只有一个作用，就是暂停setInterval()调用函数。</h3><p><img src="https://dn-mhke0kuv.qbox.me/0474fc212be6107c7c4b" alt=""></p>
<h3 id="参数id-of-settimeout的意思是："><a href="#参数id-of-settimeout的意思是：" class="headerlink" title="参数id_of_settimeout的意思是："></a>参数id_of_settimeout的意思是：</h3><p>clearTimeout是：使用clearTimeout()的函数名字，或者clearTimeout()调用的函数的名字。</p>
<p>setInterval是：使用setInterval()的函数名字，或者setInterval()调用的函数的名字。</p>
<p><strong>提示：</strong>setTimeout、setInterval在设置定时器的时候有区别，然而他们在清除定时器的时候没有区别。</p>
<p>W3C资料:<a href="http://www.w3school.com.cn/jsref/met_win_cleartimeout.asp" target="_blank" rel="noopener">clearTimeout()</a>，<a href="http://www.w3school.com.cn/jsref/met_win_clearinterval.asp" target="_blank" rel="noopener">clearInterval()</a></p>
<hr>
<h3 id="倒计时跳转demo讲解："><a href="#倒计时跳转demo讲解：" class="headerlink" title="倒计时跳转demo讲解："></a>倒计时跳转demo讲解：</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">//html相关部分：</span><br><span class="line">    &lt;div class=&quot;time&quot;&gt;请等待&lt;span id=&quot;dd&quot;&gt;5&lt;/span&gt;秒&lt;/div&gt;</span><br><span class="line">    //这里的5是初始5秒跳转。</span><br><span class="line">//js部分：</span><br><span class="line">function run()&#123;</span><br><span class="line">            var s = document.getElementById(&quot;dd&quot;);//获取dd的dom</span><br><span class="line">            if(s.innerHTML == 0)&#123;// 当dd==0的时候，跳转链接并且暂停函数</span><br><span class="line">                window.location.href = &quot;https://juejin.im/user/58714f0eb123db4a2eb95372/article&quot;;</span><br><span class="line">                clearInterval(run());//取消由 setInterval() 设置的 timeout，，这里数字暂停在0这里，否则时间会继续往下减会出现负数。</span><br><span class="line">                //setInterval调用了run()，所以setInterval的返回ID值是run（）</span><br><span class="line">            &#125;</span><br><span class="line">            s.innerHTML = s.innerHTML -1;//从5秒开始，隔一秒跑一次run()然后减1</span><br><span class="line">        &#125;</span><br><span class="line">        window.setInterval(&quot;run();&quot;, 1000); //这段代码的效果是一秒调用一次run()，</span><br><span class="line">        //“run()”是要执行的代码块，1000是时间，默认单位是毫秒</span><br></pre></td></tr></table></figure>
<p>上面这段代码主要是一个倒计时的效果，setInterval每隔一秒调用一次代码块run()，当时间被减到0的时候，暂停继续调用run()，否则会出现-1、-2的情况，然后跳转链接。<strong>具体的不懂的可以看代码注释，写的很详细。</strong></p>
<p>如果还不知道的话，可以自己做个demo试试效果就知道了。</p>
<h3 id="demo链接："><a href="#demo链接：" class="headerlink" title="demo链接："></a>demo链接：</h3><p><strong><a href="https://obkoro1.github.io/article-demo/js-time/time-countDown.html" target="_blank" rel="noopener">倒计时跳转</a></strong></p>
<h3 id="菜鸟教程也有一个demo："><a href="#菜鸟教程也有一个demo：" class="headerlink" title="菜鸟教程也有一个demo："></a>菜鸟教程也有一个demo：</h3><p><img src="https://dn-mhke0kuv.qbox.me/73b6c1d56121335f3a97.gif" alt=""></p>
<p>这也是一篇文章，写的听不错的，推荐一波！</p>
<p>链接地址：<a href="http://www.runoob.com/w3cnote/js-timer.html" target="_blank" rel="noopener">js 定时器</a></p>
<hr>
<h2 id="写在后面："><a href="#写在后面：" class="headerlink" title="写在后面："></a>写在后面：</h2><p>就十天没写文了，写的时候就感觉有点不知道怎么入手了，纠结了半天。我觉得应该把定时器的用法介绍清楚了，如果有什么地方写的不好的，欢迎指正，会在文章内勘误的。</p>
<p><strong>最后</strong>：如需转载，请放上原文链接并署名。码字不易，<strong>感谢</strong>支持！因为我经常看不懂别人写的分享，所以个人写文比较偏小白，写的不好之处，欢迎指点。然后就是希望看完的朋友点个<strong>喜欢</strong>，也可以<strong>关注</strong>一下我。<br><strong>ps</strong>：目前<strong>待业</strong>，坐标北京，本人适应互联网快节奏，高强度，持续学习，持续成长，认真，严谨，学习积极性强。<strong>中小公司大佬求带走</strong>，邮箱：<a href="mailto:obkoro1@foxmail.com" target="_blank" rel="noopener">obkoro1@foxmail.com</a>。<br><strong><a href="https://juejin.im/user/58714f0eb123db4a2eb95372" target="_blank" rel="noopener">掘金个人主页</a> </strong></p>
<h3 id="参考链接："><a href="#参考链接：" class="headerlink" title="参考链接："></a>参考链接：</h3><p><a href="http://www.runoob.com/w3cnote/js-timer.html" target="_blank" rel="noopener">js 定时器</a><br><a href="http://www.cnblogs.com/wangying731/p/5164780.html" target="_blank" rel="noopener">关于js中两种定时器的设置及清除</a><br><a href="http://www.w3school.com.cn/jsref/met_win_settimeout.asp" target="_blank" rel="noopener">w3c：setTimeout()</a>,<br><a href="http://www.jb51.net/shouce/htmldom/jb51.net.htmldom/htmldom/met_win_setinterval.asp.html" target="_blank" rel="noopener">w3c：setInterval()</a>，<br><a href="http://www.w3school.com.cn/jsref/met_win_cleartimeout.asp" target="_blank" rel="noopener">w3c：clearTimeout()</a>，<br><a href="http://www.w3school.com.cn/jsref/met_win_clearinterval.asp" target="_blank" rel="noopener">w3c：clearInterval()</a>。</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>听说，打赏我的人最后都找到了真爱。</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/pay/weixin.jpg" alt="OBKoro1 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/pay/ali.jpg" alt="OBKoro1 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/js定时器/" rel="tag"><i class="fa fa-tag"></i> js定时器</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/10/11/随机数详解-生成一个随机数，生成指定范围的随机数及随机数组去重/" rel="next" title="[随机数详解]生成一个随机数，生成指定范围的随机数及随机数组去重">
                <i class="fa fa-chevron-left"></i> [随机数详解]生成一个随机数，生成指定范围的随机数及随机数组去重
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2017/10/11/小白来实现一个Ajax请求-Ajax使用方法及相关知识点详细解析——超级全/" rel="prev" title="小白来实现一个Ajax请求[Ajax使用方法及相关知识点详细解析——超级全]">
                小白来实现一个Ajax请求[Ajax使用方法及相关知识点详细解析——超级全] <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          
            <img class="site-author-image" itemprop="image"
              src="/uploads/hand1.jpg"
              alt="OBKoro1" />
          
            <p class="site-author-name" itemprop="name">OBKoro1</p>
            <p class="site-description motion-element" itemprop="description">种一棵树最好的时间是十年前,其次是现在</p>
        </div>

        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
            
              <a href="/archives">
            
                <span class="site-state-item-count">105</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">20</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">74</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/OBKoro1" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>GitHub</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://juejin.im/user/58714f0eb123db4a2eb95372" target="_blank" title="掘金">
                  
                    <i class="fa fa-fw fa-globe"></i>掘金</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://obkoro1.com/web_accumulate/" target="_blank" title="前端积累">
                  
                    <i class="fa fa-fw fa-globe"></i>前端积累</a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://segmentfault.com/u/obkoro1/articles" target="_blank" title="segmentfault">
                  
                    <i class="fa fa-fw fa-globe"></i>segmentfault</a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#写在前面："><span class="nav-number">1.</span> <span class="nav-text">写在前面：</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#定时器的应用需求："><span class="nav-number">2.</span> <span class="nav-text">定时器的应用需求：</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#倒计时跳转实现demo："><span class="nav-number">2.1.</span> <span class="nav-text">倒计时跳转实现demo：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#js定时器："><span class="nav-number">2.2.</span> <span class="nav-text">js定时器：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用语法："><span class="nav-number">2.3.</span> <span class="nav-text">使用语法：</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#然而setTimeout-、setInterval-的区别在于"><span class="nav-number">3.</span> <span class="nav-text">然而setTimeout()、setInterval()的区别在于</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#意思就是："><span class="nav-number">3.1.</span> <span class="nav-text">意思就是：</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#那么如何暂停setTimeout-、setInterval"><span class="nav-number">4.</span> <span class="nav-text"> 那么如何暂停setTimeout()、setInterval():</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#clearTimeout（）取消由setTimeout-方法设置的-timeout。"><span class="nav-number">4.1.</span> <span class="nav-text">clearTimeout（）取消由setTimeout() 方法设置的 timeout。</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#clearInterval-，这个函数只有一个作用，就是暂停setInterval-调用函数。"><span class="nav-number">4.2.</span> <span class="nav-text">clearInterval() ，这个函数只有一个作用，就是暂停setInterval()调用函数。</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#参数id-of-settimeout的意思是："><span class="nav-number">4.3.</span> <span class="nav-text">参数id_of_settimeout的意思是：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#倒计时跳转demo讲解："><span class="nav-number">4.4.</span> <span class="nav-text">倒计时跳转demo讲解：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#demo链接："><span class="nav-number">4.5.</span> <span class="nav-text">demo链接：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#菜鸟教程也有一个demo："><span class="nav-number">4.6.</span> <span class="nav-text">菜鸟教程也有一个demo：</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#写在后面："><span class="nav-number">5.</span> <span class="nav-text">写在后面：</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#参考链接："><span class="nav-number">5.1.</span> <span class="nav-text">参考链接：</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2017 &mdash; 
  <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">OBKoro1</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">
      156.0k
    </span>
  
</div>




<div>
<script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
<span class="site-uv"><i class="fa fa-user"></i> 访问用户： <span class="busuanzi-value" id="busuanzi_value_site_uv">21621</span> 人 </span>
<span class="site-pv"><i class="fa fa-eye"></i> 访问次数： <span class="busuanzi-value" id="busuanzi_value_site_pv">68503</span> 次</span>

</div>



        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>

  
  <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.2"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.2"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.2"></script>



  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.2"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.2"></script>


  

  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.2"></script>



  


  




	





  





  








  



  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("9ANFp60h6oVyxIPGlau3NOA4-gzGzoHsz", "tMdNuKMbFtN4QsekeNVu83TV");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  

  

  

</body>
</html>

